﻿
//---------------------------------------------------
$.fn.json_serialize = function () {
    var a = this.serializeArray();
    var $radio = $('input[type=radio],input[type=checkbox]', this);
    $.each($radio, function () {
        if ($("input[name='" + this.name + "']").is(':checked')) {
            console.log(this.name + " is checked!");
            for (var k = 0; k < a.length; k++) {
                if (a[k].name == this.name) {
                    a[k].value = true;
                    break;
                }
            }
        } else {
            var find = false;
            for (var k = 0; k < a.length; k++) {
                if (a[k].name == this.name) {
                    a[k].value = false;
                    find = true;
                    break;
                }
            }
            if (!find) {
                a.push({ name: this.name, value: false });
            }
        }
    });
    var $num = $('input[type=number]', this);
    $.each($num, function () {
        for (var k = 0; k < a.length; k++) {
            if (a[k].name == this.name) {
                a[k].value = Number(a[k].value);
                break;
            }
        }
    });

    var $snum = $('select', this);
    $.each($snum, function () {
        for (var k = 0; k < a.length; k++) {
            if (a[k].name == this.name) {
                var val =a[k].value;
                if(new RegExp("^[0-9,\-]$").test(val)){
                    a[k].value = Number(a[k].value);
                }
                // a[k].value = Number(a[k].value);
                break;
            }
        }
    });



    return a;
};

$.fn.parseForm = function () {
    let serializeObj = {};
    let array = this.json_serialize();
    //let str = this.serialize();
    $(array).each(function () {
        if (serializeObj[this.name]) {
            if ($.isArray(serializeObj[this.name])) {
                serializeObj[this.name].push(this.value);
            } else {
                serializeObj[this.name] = [serializeObj[this.name], this.value];
            }
        } else {
            serializeObj[this.name] = this.value;
        }
    });
    return serializeObj;
};
//————————————————===================

var _waitloading = 500;

/**
 * 
 * @param {*} httpurl 
 * @param {*} async 
 * @param {*} callback 
 */
function _apiget(httpurl, async, callback) {

    var loadid = 0;
    var ajaxcompleted = false;
    var tickevent = function () {
        if (!ajaxcompleted) {
            if (typeof (layer) != "undefined") {
                loadid = layer.load();
            }
        }
    }
    setTimeout(tickevent, _waitloading);

    $.ajax({
        //提交数据的类型 POST GET
        type: "GET",
        //提交的网址
        url: httpurl,
        async: async,
        //提交的数据
        //data: postdata,
        //返回数据的格式
        datatype: "jsonp",//"xml", "html", "script", "json", "jsonp", "text".
        headers: {
            "token": readToken()
        },
        //在请求之前调用的函数
        beforeSend: function (request) {
        },
        //成功返回之后调用的函数
        success: function (data) {
            //console.log("执行到了success");
        },
        //调用执行后调用的函数
        complete: function (XMLHttpRequest, textStatus) {
            ajaxcompleted = true;
            _funccallback(XMLHttpRequest, loadid, callback);
        },
        //调用出错执行的函数
        error: function () {
            //请求出错处理
            //console.log("执行到了error");
        }
    });
}

/**
 * 
 * @param {*} httpurl 
 * @param {*} async 
 * @param {*} data 
 * @param {*} callback 
 */
function _apipost(httpurl, async, data, callback) {

    var loadid = 0;
    var ajaxcompleted = false;
    var tickevent = function () {
        if (!ajaxcompleted) {
            if (typeof (layer) != "undefined") {
                loadid = layer.load();
            }
        }
    }
    setTimeout(tickevent, _waitloading);

    $.ajax({
        //提交数据的类型 POST GET
        type: "POST",
        //提交的网址
        url: httpurl,
        async: async,
        //提交的数据
        data: data,
        //返回数据的格式
        datatype: "jsonp",//"xml", "html", "script", "json", "jsonp", "text".
        headers: {
            "token": readToken()
        },
        contentType: "application/json; charset=UTF-8",
        //在请求之前调用的函数
        beforeSend: function (request) {
            //request.setRequestHeader("order", order);
        },
        //成功返回之后调用的函数
        success: function (data) {
            //console.log("执行到了success");
        },
        //调用执行后调用的函数
        complete: function (XMLHttpRequest, textStatus) {
            //console.log(XMLHttpRequest);
            ajaxcompleted = true;

            _funccallback(XMLHttpRequest, loadid, callback);

        },
        //调用出错执行的函数
        error: function () {
            //请求出错处理
            //console.log("执行到了error");
        }
    });
}

function _funccallback(XMLHttpRequest, loadid, callback) {

    if (XMLHttpRequest.status == 401 || XMLHttpRequest.status == 403) {

        if (typeof (layer) != "undefined") {
            layer.msg("当前操作需要登录！", { time: 1500 }, function () {
                window.parent.location.href = "/page/login/index.html?t=" + (new Date()).getTime();
            });
        } else {
            window.parent.location.href = "/page/login/index.html?t=" + (new Date()).getTime();
        }

    } else if (XMLHttpRequest.status == 204) {
        if (typeof (layer) != "undefined") {
            layer.msg("查询数据为空");
        } else {
            alert("查询数据为空");
        }
    } else {

        if (XMLHttpRequest.status == 200) {
            // var result = JSON.parseXMLHttpRequest.responseText;
            var responsestr = XMLHttpRequest.responseText;
            if (responsestr[0] == "{" || responsestr[0] == "[") {
                callback(XMLHttpRequest.status, JSON.parse(XMLHttpRequest.responseText));
            } else {
                callback(XMLHttpRequest.status, (XMLHttpRequest.responseText));
            }
        } else {

            var responsestr = XMLHttpRequest.responseText;
            if (responsestr.length > 0) {

                if (responsestr[0] == "{" || responsestr[0] == "[") {

                    var errinfo = JSON.parse(XMLHttpRequest.responseText);
                    if (errinfo.message) {
                        if (typeof (layer) != "undefined") {
                            layer.msg(errinfo.message);
                        } else {
                            alert(errinfo.message);
                        }
                    }
                    callback(XMLHttpRequest.status, errinfo);
                } else {
                    if (typeof (layer) != "undefined") {
                        // layer.closeAll();
                        layer.msg(responsestr);
                    } else {
                        alert(responsestr);
                    }

                    callback(XMLHttpRequest.status, responsestr);
                }

            } else {

                var errmessage = "请求API遇到一个错误！";

                if (typeof (layer) != "undefined") {
                    // layer.closeAll();
                    layer.msg(errmessage);
                } else {
                    alert(errmessage);
                }
            }

        }

    }

    if (loadid > 0) {
        if (typeof (layer) != "undefined") {
            layer.close(loadid);
        }
    }
}

function _apigetquery(key) {
    // 获取参数
    var url = window.location.search;
    // 正则筛选地址栏
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
    // 匹配目标参数
    var result = url.substr(1).match(reg);
    //返回参数值
    return result ? decodeURIComponent(result[2]) : null;
}


function readToken() {
    return _locReadData("webtoken");
}
function saveToken(sval) {
    if (sval.length > 0) {
        _locSaveData("webtoken", sval);
    } else {
        localStorage.removeItem("webtoken");
    }
}

function _locSaveData(skey, sval) {
    localStorage.setItem(skey, sval);
}

function _locReadData(skey) {
    return localStorage.getItem(skey);
}

//=====================================

/**
 * 打开编辑页面
 * @param {any} title
 * @param {any} url
 * @param {any} id
 * @param {any} w
 * @param {any} h
 */
function _showedit(title, url, id, w, h) {

    if (url.indexOf('?') > 0) {
        layer_show(title, url + "&id=" + id, w, h);
    } else {
        layer_show(title, url + "?id=" + id, w, h);
    }


}

/**
 * 
 * @param {*} title 
 * @param {*} url 
 * @param {*} w 
 * @param {*} h 
 */
function _showwindow(title, url, w, h) {
    layer_show(title, url, w, h);
}

/**
 * 打开新增页面
 * @param {any} title
 * @param {any} url
 * @param {any} w
 * @param {any} h
 */
function _showadd(title, url, w, h) {
    layer_show(title, url, w, h);
}

//Array的扩展
Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};

Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

String.prototype.Format=function(fmt){
    var date=new Date(this.replace(/-/g,'/'));
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "H+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


function isPicture(name) {
    //判断是否是图片 - strFilter必须是小写列举
    var strFilter = ".jpeg|.gif|.jpg|.png|.bmp|.pic|.webp|"
    if (name.indexOf(".") > -1) {
        var p = name.lastIndexOf(".");
        var strPostfix = name.substring(p, name.length) + '|';
        strPostfix = strPostfix.toLowerCase();
        if (strFilter.indexOf(strPostfix) > -1) { return true; }
    }
    return false;
}
/**
 * 
 * @param {*} obj 
 */
function _bindelement(obj) {
    for (var key in obj) {
        var objdom = $("[name=" + key + "]");
        if (objdom.length > 0) {
            var tagname = objdom[0].tagName;
            if (tagname == "INPUT") {
                var type = objdom[0].type;
                if (type == "checkbox") {
                    // console.log(obj[key]);
                    if (obj[key] || obj[key] === 1) {
                        objdom.prop("checked", true);
                        objdom.parent().addClass("checked");
                    } else {
                        objdom.prop("checked", false);
                    }
                } else {
                    objdom.val(obj[key]);
                }
            } else if (tagname == "SELECT") {
                objdom.val(obj[key]);
            } else if (tagname == "TEXTAREA") {
                objdom.val(obj[key]);
            }
            else if (tagname == "IMG") {
                objdom.attr('src', obj[key]);
            } else if (tagname == "DIV") {
                objdom.html(obj[key]);
            }
        }
    }
}
/**
 * 根据javascript text/html构建对象，最多支持3级
 * @param {*} html 
 * @param {*} obj 
 * @returns 
 */
function _buildtemplate(html, obj) {
    //\[([^\[\]]*?)\]
    var reg = new RegExp("\\[([^\\[\\]]*?)\\]", 'igm');
    // var html = document.getElementById("orderdetailhtml").innerHTML;
    var _innerhtml = html.replace(reg, function (node, key) {
        if (key.indexOf(":") > 0) {
            var keys = key.split(':');
            switch (keys.length) {
                case 2:{
                    if(obj[keys[0]]!=null){
                        return obj[keys[0]][keys[1]]
                    }else{
                        return "";
                    }
                };
                case 3:
                    {
                        if(obj[keys[0]]!=null){
                            if(obj[keys[0]][keys[1]]!=null){
                                return obj[keys[0]][keys[1]][keys[2]];
                            }else{
                                return "";
                            }
                        }else{
                            return "";
                        }


                    };
                case 4:
                    {
                        if(obj[keys[0]]!=null){
                            if(obj[keys[0]][keys[1]]!=null){
                                if(obj[keys[0]][keys[1]][keys[2]]!=null){
                                    return obj[keys[0]][keys[1]][keys[2]][keys[3]];
                                }else{
                                    return "";
                                }
                            }else{
                                return "";
                            }
                        }else{
                            return "";
                        }
                    };
                default: return obj[keys[0]][keys[1]];
            }
        } else {
            return obj[key];
        }
    });
    return _innerhtml;
}


/**
 * 前端验证
 * @param {*} elcselect 
 * @returns 
 */
function _beforeValidity(elcselect) {

    var findvalid = true;
    var fileds = $(elcselect)[0].querySelectorAll(":invalid");
    for (var k = 0; k < fileds.length; k++) {
        var namestr = fileds[k].name;
        var valinfo = fileds[k].validity;
        if (!valinfo.valid) {
            findvalid = false;
            if (valinfo.valueMissing) {
                layer.tips('当前项必须填写', elcselect + " [name=" + namestr + "]",{tipsMore:true},1);
            }
            if (valinfo.typeMismatch) {
                layer.tips('输入的数据类型不匹配，请按需输入', elcselect + " [name=" + namestr + "]", {tipsMore:true},1);
            }

            if (valinfo.patternMismatch) {
                layer.tips('输入的数据格式不匹配，请按需输入', elcselect + " [name=" + namestr + "]", {tipsMore:true},1);
            }

            if (valinfo.tooLong) {
                layer.tips('输入的数据位数过大，请按需输入', elcselect + " [name=" + namestr + "]", {tipsMore:true},1);
            }
            if (valinfo.tooShort) {
                layer.tips('输入的数据位数不足，请按需输入', elcselect + " [name=" + namestr + "]", {tipsMore:true},1);
            }

            if (valinfo.rangeOverflow) {
                layer.tips('输入的数据过大，请按需输入', elcselect + " [name=" + namestr + "]", {tipsMore:true},1);
            }

            if (valinfo.rangeUnderflow) {
                layer.tips('输入的数据过小，请按需输入', elcselect + " [name=" + namestr + "]", {tipsMore:true},1);
            }
        }
    }
    return findvalid;
}

